<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <div v-if="formType != 'change'">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
      >
        <el-form-item label="单据号" prop="billNo">
          <el-input v-model="formData.billNo" placeholder="请输入单据号" />
        </el-form-item>
        <el-form-item label="房产id" prop="detail[0].houseId" v-show="false">
          <el-input v-model="formData.detail[0].houseId" placeholder="请输入房产id" />
        </el-form-item>
        <el-form-item label="房产名称" prop="detail[0].houseName">
          <el-input readonly v-model="formData.detail[0].houseName" placeholder="请输入房产id" />
        </el-form-item>
        <el-form-item label="客户id" prop="detail[0].customerId">
          <el-input v-model="formData.detail[0].customerId" placeholder="请输入客户id" />
        </el-form-item>
        <el-form-item label="设备id" prop="detail[0].equipId" v-show="false">
          <el-input disabled v-model="formData.detail[0].equipId" placeholder="请输入设备id" />
        </el-form-item>
        <el-form-item label="设备名称" prop="detail[0].equipName">
          <el-input readonly v-model="formData.detail[0].equipName" placeholder="请输入设备id" />
        </el-form-item>
        <el-form-item label="生效时间" prop="detail[0].effTime">
          <el-date-picker
            v-model="formData.detail[0].effTime"
            type="date"
            value-format="x"
            placeholder="选择生效时间"
            class="!w-1/1"
          />
        </el-form-item>
        <el-form-item
          :label="busScope == '0' ? '行码' : busScope == '1' ? '表码' : '蒸汽量读数'"
          prop="detail[0].bv01"
        >
          <el-input v-model="formData.detail[0].bv01" placeholder="请输入读数" />
        </el-form-item>
        <el-form-item v-if="busScope == '1'" label="尖" prop="detail[0].bv02">
          <el-input v-model="formData.detail[0].bv02" placeholder="请输入读数" />
        </el-form-item>
        <el-form-item v-if="busScope == '1'" label="峰" prop="detail[0].bv03">
          <el-input v-model="formData.detail[0].bv03" placeholder="请输入读数" />
        </el-form-item>
        <el-form-item v-if="busScope == '1'" label="平" prop="detail[0].bv04">
          <el-input v-model="formData.detail[0].bv04" placeholder="请输入读数" />
        </el-form-item>
        <el-form-item v-if="busScope == '1'" label="谷" prop="detail[0].bv05">
          <el-input v-model="formData.detail[0].bv05" placeholder="请输入读数" />
        </el-form-item>
        <el-form-item label="备注" prop="detail[0].rem1">
          <el-input v-model="formData.detail[0].rem1" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="图片" prop="detail[0].vdef1">
          <UploadImgs v-model="formData.detail[0].vdef1" class="min-w-80px" :limit="5" />
        </el-form-item>
      </el-form>
    </div>
    <div class="mx-auto" v-else>
      <el-steps :active="active" finish-status="success">
        <el-step title="更换前" />
        <el-step title="更换后" />
      </el-steps>
      <div class="mt-50px">
        <div v-if="active === 0" class="mx-auto w-560px">
          <EquipBeforeChangeRec
            v-model="formData"
            :busScope="busScope"
            ref="equipBeforeChangeRecRef"
            v-loading="formLoading"
          />
        </div>
        <div v-else class="mx-auto w-560px">
          <EquipAfterChangeRec
            v-model="formData"
            :busScope="busScope"
            ref="equipAfterChangeRecRef"
            v-loading="formLoading"
          />
        </div>
      </div>
      <div class="flex justify-center">
        <el-button v-if="previousShow" type="primary" @click="previous()">上一步</el-button>
        <el-button v-if="nextShow" type="primary" @click="next">下一步</el-button>
      </div>
    </div>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { EquipHouseApi, EquipRecVO, EquipHouseVO } from '@/api/iotmanage/equiphouse'
import EquipBeforeChangeRec from './form/EquipBeforeChangeRec.vue'
import EquipAfterChangeRec from './form/EquipAfterChangeRec.vue'
const active = ref(0)
const previousShow = ref(false)
const nextShow = ref(true)
/** 换表表底记录 表单 */
defineOptions({ name: 'EquipRecForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  type: undefined as unknown | string,
  billNo: undefined,
  detail: [
    {
      id: undefined,
      equipId: undefined as undefined | number,
      houseId: undefined as undefined | number,
      customerId: undefined,
      effTime: undefined,
      bv01: undefined,
      bv02: undefined,
      bv03: undefined,
      bv04: undefined,
      bv05: undefined,
      rem1: undefined,
      houseName: undefined,
      equipName: undefined
    },
    {
      id: undefined,
      equipId: undefined,
      houseId: undefined,
      customerId: undefined,
      effTime: undefined,
      bv01: undefined,
      bv02: undefined,
      bv03: undefined,
      bv04: undefined,
      bv05: undefined,
      rem1: undefined,
      houseName: undefined,
      equipName: undefined
    }
  ]
})
const formRules = reactive({
  'detail[0].equipId': [{ required: true, message: '设备id不能为空', trigger: 'blur' }],
  'detail[0].effTime': [{ required: true, message: '生效时间不能为空', trigger: 'blur' }],
  'detail[0].bv01': [{ required: true, message: '读数不能为空', trigger: 'blur' }],
  'detail[0].bv02': [{ required: true, message: '读数不能为空', trigger: 'blur' }],
  'detail[0].bv03': [{ required: true, message: '读数不能为空', trigger: 'blur' }],
  'detail[0].bv04': [{ required: true, message: '读数不能为空', trigger: 'blur' }],
  'detail[0].bv05': [{ required: true, message: '读数不能为空', trigger: 'blur' }],
  'detail[0].houseId': [{ required: true, message: '房产id不能为空', trigger: 'blur' }],
  'detail[0].customerId': [{ required: true, message: '客户id不能为空', trigger: 'blur' }],
  billNo: [{ required: true, message: '单据号不能为空', trigger: 'blur' }],
  'detail[0].vdef1': [{ required: true, message: '图片不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const busScope = ref()
// 组件引用
const equipBeforeChangeRecRef = ref()
const equipAfterChangeRecRef = ref()
//步骤校验函数
const validateBeforeChangeRec = async () => {
  await equipBeforeChangeRecRef.value?.validate()
}
const validateAfterChangeRec = async () => {
  await equipAfterChangeRecRef.value?.validate()
}
//添加组件卸载前的清理代码
onBeforeUnmount(() => {
  // 卸载组件时，清除引用
  equipBeforeChangeRecRef.value = null
  equipAfterChangeRecRef.value = null
})
const next = async () => {
  try {
    await handleStepClick(active.value)
    active.value++
    if (active.value > 0) {
      previousShow.value = true
      nextShow.value = false
    }
  } catch (error) {
    console.error('步骤切换失败:', error)
    message.warning('请先完善当前步骤必填信息')
  }
}
const previous = async () => {
  try {
    await handleStepClick(active.value)
    active.value--
    if (active.value <= 0) {
      previousShow.value = false
      nextShow.value = true
    }
  } catch (error) {
    console.error('步骤切换失败:', error)
    message.warning('请先完善当前步骤必填信息')
  }
}
const handleStepClick = async (active: number) => {
  try {
    if (active == 0) {
      console.log(active)
      await validateBeforeChangeRec()
    } else {
      console.log(active)
      await validateAfterChangeRec()
    }
  } catch (error) {
    throw error
  }
}
/** 打开弹窗 */
const open = async (type: string, vo: EquipHouseVO) => {
  dialogVisible.value = true
  dialogTitle.value = type == 'install' ? '安装' : type == 'change' ? '更换' : '拆除'
  formType.value = type
  resetForm()
  const res = await EquipHouseApi.getEquipHouse(vo.id)
  // 设置数据
  formData.value.detail[0].equipId = vo.id // 设备id
  formData.value.detail[0].houseId = vo.houseId // 房产id
  formData.value.detail[1].houseId = vo.houseId //房产id
  formData.value.detail[0].equipName = res.name // 设备名称
  formData.value.detail[0].houseName = res.houseName // 房产名称
  formData.value.detail[1].houseName = res.houseName // 房产名称
  busScope.value = vo.busScope
  formData.value.type = type
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (formType.value === 'change') {
    await validateBeforeChangeRec()
    await validateAfterChangeRec()
  } else {
    await formRef.value.validate()
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as EquipRecVO
    await EquipHouseApi.operateEquipRec(data)
    message.success(
      formType.value === 'install'
        ? '安装成功'
        : formType.value === 'change'
          ? '更换成功'
          : '拆除成功'
    )
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    type: undefined,
    billNo: undefined,
    detail: [
      {
        id: undefined,
        equipId: undefined,
        houseId: undefined,
        customerId: undefined,
        effTime: undefined,
        bv01: undefined,
        bv02: undefined,
        bv03: undefined,
        bv04: undefined,
        bv05: undefined,
        rem1: undefined,
        houseName: undefined,
        equipName: undefined
      },
      {
        id: undefined,
        equipId: undefined,
        houseId: undefined,
        customerId: undefined,
        effTime: undefined,
        bv01: undefined,
        bv02: undefined,
        bv03: undefined,
        bv04: undefined,
        bv05: undefined,
        rem1: undefined,
        houseName: undefined,
        equipName: undefined
      }
    ]
  }
  formRef.value?.resetFields()
  active.value = 0
  previousShow.value = false
  nextShow.value = true
}
</script>
